//
//  OrderVC.m
//  easyTaxi
//
//  Created by ellenpage on 12-12-7.
//  Copyright (c) 2012年 ellenpage. All rights reserved.
//

#import "OrderTBCell.h"
#import "Constant.h"
#import "OrderVC.h"
#import "ViewAnimation.h"
#import "RequestCMD.h"
#import "SocketObject.h"
#import "PullingRefreshTableView.h"
#import "PassValueClass.h"
#import "MBProgressHUD.h"
#import "SysViewObject.h"
#import "Constant.h"

#import "BMapKit.h"
#import "BMKMapView.h"

#define kIsFirstTimeCame @"isFirstTimeCame"//首次进入

#define kMianRect CGRectMake(0,0,320,500)
#define kRect     CGRectMake(10,74,300,332)

@interface OrderVC ()<UITextViewDelegate,UITableViewDataSource,UITableViewDelegate,PullingRefreshTableViewDelegate,MFMessageComposeViewControllerDelegate,BMKMapViewDelegate,BMKAnnotation>

@property (strong, nonatomic) IBOutlet UIView *finishedOrderView;
@property (weak, nonatomic)   IBOutlet UIButton *btn1;
@property (weak, nonatomic)   IBOutlet UIButton *btn2;

@property (retain, nonatomic) PullingRefreshTableView *mTBView;
@property (retain, nonatomic) PullingRefreshTableView *mTBView2;

@property (weak, nonatomic)   IBOutlet UITextView *badEvaluateTxtView;
@property (weak, nonatomic)   IBOutlet UITextView *goodEvaluateTxtView;

@property (retain, nonatomic) NSMutableArray *dataArray;
@property (retain, nonatomic) NSMutableArray *dataArray_Finished;
@property (retain, nonatomic) MBProgressHUD *HD;

@property (retain, nonatomic) UIView *blackView;

@property (weak, nonatomic)   IBOutlet UILabel *totalNumber;
@property (weak, nonatomic)   IBOutlet UILabel *totalNumber_Finished;

@property (retain, nonatomic) NSString *depLat;
@property (retain, nonatomic) NSString *depLng;//起点经纬度

@property (retain, nonatomic) NSString *desLat;
@property (retain, nonatomic) NSString *desLng;//终点经纬度

@property (retain, nonatomic) BMKMapView *mapView;
@property (weak, nonatomic)   IBOutlet UIView *mapView_Small;

- (IBAction)resignAllKeyboard;

- (void)addTBView;
- (void)loadTBViewData;
- (void)loadTBViewData2;
- (IBAction)showSysView;

@end

@implementation OrderVC

#pragma mark - System Function - 系统函数

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self  loadData];
    
    [self  loadTBViewData];
    [self  loadTBViewData2];
    
    [self  loadMap];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    [self setFinishedOrderView:nil];
    [self setBtn1:nil];
    [self setBtn2:nil];
    [self setMTBView:nil];
    [self setMTBView2:nil];
    [self setBadEvaluateTxtView:nil];
    [self setGoodEvaluateTxtView:nil];
    [self setTotalNumber:nil];
    [self setTotalNumber_Finished:nil];
    [self setGoodEvaluateView:nil];
    [self setBadEvaluateView:nil];
    [self setBadEvaluateView_Small:nil];
    [self setGoodEvaluateView_Small:nil];
    [self setUnEvaluateNoLbl:nil];
    [self setEvaluateNoLbl:nil];
    [self setMyMapView:nil];
    [self setMapView_Small:nil];
    [super viewDidUnload];
}

#pragma mark - 

- (void)loadData
{
    _finishedOrderView.frame = kMianRect;
    [self.view addSubview:_finishedOrderView];
    _finishedOrderView.hidden = YES;
    
    _mTBView  = [[PullingRefreshTableView alloc] initWithFrame:kRect pullingDelegate:self];
    _mTBView.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.35];
    _mTBView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_mTBView.layer setCornerRadius:4];
    [_mTBView.layer setBorderColor:[[UIColor whiteColor] CGColor]];//描边颜色
    [_mTBView.layer setBorderWidth:2.0];//描边粗细
    [self.view addSubview:_mTBView];
    
    _mTBView2 = [[PullingRefreshTableView alloc] initWithFrame:kRect pullingDelegate:self];
    _mTBView2.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.35];
    _mTBView2.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_mTBView2.layer setCornerRadius:4];
    [_mTBView2.layer setBorderColor:[[UIColor redColor] CGColor]];//描边颜色
    [_mTBView2.layer setBorderWidth:2.0];//描边粗细
    [_finishedOrderView addSubview:_mTBView2];
    
    _mTBView.delegate  = self;
    _mTBView2.delegate = self;
    
    _mTBView.dataSource  = self;
    _mTBView2.dataSource = self;
    
    _mTBView.pullingDelegate  = self;
    _mTBView2.pullingDelegate = self;

    _blackView = [[UIView alloc] initWithFrame:kMianRect];
    _blackView.backgroundColor = [UIColor blackColor];
    [self.view insertSubview:_blackView belowSubview:_finishedOrderView];
    _blackView.hidden = YES;

    _goodEvaluateTxtView.delegate = self;
    _badEvaluateTxtView.delegate  = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTBView) name:kGetUnevaluatedBill object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTBView2) name:kGetevaluatedBill object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.view addSubview:[SysViewObject sharedIntance].sysView];
    [SysViewObject sharedIntance].sysView.hidden = YES;
    
    [YouMengEvent YouMengEvent:kPingJia_YouMeng];
}

-(void)pullingTableViewDidStartLoading:(PullingRefreshTableView *)tableView
{
    if (_finishedOrderView.hidden == YES)
    {
        [self loadTBViewData];
    }
    else
    {
        [self loadTBViewData2];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_mTBView tableViewDidScroll:scrollView];
    [_mTBView2 tableViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [_mTBView tableViewDidEndDragging:scrollView];
    [_mTBView2 tableViewDidEndDragging:scrollView];
}


- (IBAction)goYuYueView
{
    [self selectPage:1];
}

- (IBAction)goDaiJiaView
{
    [self selectPage:2];
}

- (void)selectPage:(NSInteger)i
{
    switch (i) {
        case 1:
        {
            if (_finishedOrderView.hidden == NO)
            {
                _mTBView2.hidden = YES;
                _blackView.hidden = NO;
                [ViewAnimation viewAnimation:3 view:_finishedOrderView];
                _finishedOrderView.hidden = YES;
                [self performSelector:@selector(hiddenBlackView) withObject:nil afterDelay:0.5f];
            }
            [_btn1 setImage:[UIImage imageNamed:@"tab_left1.png"] forState:UIControlStateNormal];
            [_btn2 setImage:[UIImage imageNamed:@"tab_right0.png"] forState:UIControlStateNormal];
        }
            break;
            
        case 2:
        {
            _mTBView.hidden  = YES;
            if (_finishedOrderView.hidden == YES)
            {
                _blackView.hidden = NO;
                [ViewAnimation viewAnimation:2 view:_finishedOrderView];
                _finishedOrderView.hidden = NO;
                [self performSelector:@selector(hiddenBlackView) withObject:nil afterDelay:1.0f];
            }
            [_btn2 setImage:[UIImage imageNamed:@"tab_right1.png"] forState:UIControlStateNormal];
            [_btn1 setImage:[UIImage imageNamed:@"tab_left0.png"] forState:UIControlStateNormal];
        }
            break;
            
        default:
            break;
    }
}

- (void)hiddenBlackView
{
    if (_finishedOrderView.hidden == YES)
    {
        _mTBView2.hidden  = YES;
        _mTBView.hidden   = NO;
    }
    else
    {
        _mTBView.hidden   = YES;
        _mTBView2.hidden  = NO;
    }
    _blackView.hidden = YES;
    [_mTBView reloadData];
    [_mTBView2 reloadData];
}

- (IBAction)resignAllKeyboard
{
    [_goodEvaluateTxtView resignFirstResponder];
    [_badEvaluateTxtView  resignFirstResponder];
}

- (void)loadTBViewData
{
    bool noMoreUnevaluatedBill = [PassValueClass sharedIntance].noMoreUnevultedBill;
    if (noMoreUnevaluatedBill)
    {
        [_mTBView tableViewDidFinishedLoading];
    }
    else
    {
        [PassValueClass sharedIntance].pageIndex ++;
        NSLog(@"pageIndex = %d",[PassValueClass sharedIntance].pageIndex);
        
        //--------------------1055---未评价订单
        NSString *string    = [RequestCMD requestCMD:kBillUnevaluated];
        NSMutableData *data = [RequestCMD getWantedData:string];
        [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kBillUnevaluated];//1055---未评价订单
    }
}

- (void)loadTBViewData2
{
    bool noMoreevaluatedBill = [PassValueClass sharedIntance].noMoreevultedBill;
    if (noMoreevaluatedBill)
    {
        [_mTBView2 tableViewDidFinishedLoading];
    }
    else
    {
        [PassValueClass sharedIntance].pageIndex_Finished ++;
        NSLog(@"%d",[PassValueClass sharedIntance].pageIndex_Finished);
        
        //--------------------1057---已经评价订单
        NSString *string    = [RequestCMD requestCMD:kBillEvaluated];
        NSMutableData *data = [RequestCMD getWantedData:string];
        [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kBillEvaluated];//1057---已经评价订单
    }
}

- (IBAction)showSysView
{
    if ([SysViewObject sharedIntance].sysView.hidden == YES)
    {
        [SysViewObject sharedIntance].sysView.hidden = NO;
    }
}
    

#pragma mark - NSNotificationCenter - 用户通知

- (void)reloadTBView
{
    NSArray *tmpArray = [PassValueClass sharedIntance].unevaluatedArray;
    _dataArray = [NSMutableArray arrayWithArray:tmpArray];
    NSLog(@"_dataArray = %@",_dataArray);
    [_mTBView reloadData];
}

- (void)reloadTBView2
{
    NSArray *tmpArray = [PassValueClass sharedIntance].evaluatedArray;
    _dataArray_Finished = [NSMutableArray arrayWithArray:tmpArray];
    NSLog(@"_dataArray_Finished = %@",_dataArray_Finished);
    [_mTBView2 reloadData];
}


#pragma mark - TableViewDataSource Delegate - TableView Datasource代理

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_finishedOrderView.hidden == YES)
    {
        _unEvaluateNoLbl.text = [NSString stringWithFormat:@"%d",_dataArray.count];
        return [_dataArray count];
    }
    else
    {
        _evaluateNoLbl.text = [NSString stringWithFormat:@"%d",_dataArray_Finished.count];
        return [_dataArray_Finished count];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderTBCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderTBCell"];
    if (!cell)
    {
        cell = [OrderTBCell getInstance];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    NSArray *tmpArray;
    if (_finishedOrderView.hidden == YES)
    {
        tmpArray = [NSArray arrayWithArray:_dataArray];
    }
    else
    {
        tmpArray = [NSArray arrayWithArray:_dataArray_Finished];
    }
    
    if (tmpArray.count > 0)
    {
        NSDictionary *dict = [tmpArray objectAtIndex:indexPath.row];
        
        //类型
        NSString *typeStr = [dict objectForKey:kRequestType];
        if ([typeStr isEqualToString:@"1"])
        {
            cell.imgView.image = [UIImage imageNamed:@"taketaxipicsmall.png"];
        }
        if ([typeStr isEqualToString:@"2"])
        {
            cell.imgView.image = [UIImage imageNamed:@"thirdpicsmall.png"];
        }
        if ([typeStr isEqualToString:@"3"])
        {
            cell.imgView.image = [UIImage imageNamed:@"appointpicsmall.png"];
        }
                
        //发布时间
        NSString *timeStr = [dict objectForKey:kPostTime];
        cell.dateLbl.text = timeStr;
        
        //起始地经纬度
        NSString *curLat = [dict objectForKey:kCurLatitude];
        NSString *curLng = [dict objectForKey:kCurLongitude];
        cell.depatureBtn.tag = indexPath.row;
        cell.depatureBtn.hidden = YES;

        if (![curLat isEqualToString:@"0"]&& ![curLng isEqualToString:@"0"])
        {
            _depLat = curLat;
            _depLng = curLng;
            cell.depatureBtn.hidden = NO;
            [cell.depatureBtn addTarget:self action:@selector(showDepture) forControlEvents:UIControlEventTouchUpInside];
        }
        
        //目的地经纬度
        NSString *desLat = [dict objectForKey:kDesLatitude];
        NSString *desLng = [dict objectForKey:kDesLongitude];
        cell.destinationBtn.tag = indexPath.row;
        cell.destinationBtn.hidden = YES;

        if (![desLat isEqualToString:@"0"]&& ![desLng isEqualToString:@"0"])
        {
            _desLat = desLat;
            _desLng = desLng;
            cell.destinationBtn.hidden = NO;
            [cell.destinationBtn addTarget:self action:@selector(showDestination) forControlEvents:UIControlEventTouchUpInside];

        }

        //司机姓名
        NSString *nickStr = [dict objectForKey:kNick];
        cell.driverNameLbl.text = nickStr;
        
        //车牌号
        NSString *hmmpStr = [dict objectForKey:kHPHM];
        cell.driverIDLbl.text = hmmpStr;
        
        //司机评价
        NSString *driverEvaluateStr = [dict objectForKey:kDriverEvaluate];
        if ([driverEvaluateStr isEqualToString:@"0"])
        {
            cell.evaluateLbl.text = @"未评";
        }
        if ([driverEvaluateStr isEqualToString:@"1"])
        {
            cell.evaluateLbl.text = @"好评";
        }
        if ([driverEvaluateStr isEqualToString:@"2"])
        {
            cell.evaluateLbl.text = @"差评";
        }

        if (_finishedOrderView.hidden == YES)
        {
            cell.userEvaluateLbl.hidden = YES;
            cell.goodEvaluateBtn.tag = indexPath.row;
            cell.badEvaluateBtn.tag  = indexPath.row;
            
            [cell.goodEvaluateBtn addTarget:self
                                     action:@selector(goodEvaluate:)
                           forControlEvents:UIControlEventTouchUpInside];
            
            [cell.badEvaluateBtn addTarget:self
                                    action:@selector(badEvaluate:)
                          forControlEvents:UIControlEventTouchUpInside];

        }
        else
        {
            cell.userEvaluateLbl.hidden = NO;
            cell.goodEvaluateBtn.hidden = YES;
            cell.badEvaluateBtn.hidden  = YES;
            
            NSString *userEvaluateStr = [dict objectForKey:kUserEvaluate];

            if ([userEvaluateStr isEqualToString:@"0"])
            {
                cell.userEvaluateLbl.text = @"未评";
            }
            if ([userEvaluateStr isEqualToString:@"1"])
            {
                cell.userEvaluateLbl.text = @"好评";
            }
            if ([userEvaluateStr isEqualToString:@"2"])
            {
                cell.userEvaluateLbl.text = @"差评";
            }
        }
    }
    NSLog(@"cell:%@", cell);
    return cell;
}

- (void)showDepture
{
    _myMapView.hidden = NO;
    
    NSArray *annotations = [NSArray arrayWithArray:_mapView.annotations];
    for (BMKPointAnnotation *annotation in annotations)
    {
        [self.mapView removeAnnotation:annotation];
    }

    CLLocationCoordinate2D coor;
    coor.latitude  = [_depLat floatValue];
    coor.longitude = [_depLng floatValue];
    
    BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init];
    annotation.title = @"起始地";
    annotation.coordinate = coor;
    [_mapView addAnnotation:annotation];
    [_mapView selectAnnotation:annotation animated:YES];
}


- (void)showDestination
{
    _myMapView.hidden = NO;
    
    NSArray *annotations = [NSArray arrayWithArray:_mapView.annotations];
    for (BMKPointAnnotation *annotation in annotations)
    {
        [self.mapView removeAnnotation:annotation];
    }

    CLLocationCoordinate2D coor;
    coor.latitude  = [_desLat floatValue];
    coor.longitude = [_desLng floatValue];
    
    BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init];
    annotation.title = @"目的地";
    annotation.coordinate = coor;
    [_mapView addAnnotation:annotation];
    [_mapView selectAnnotation:annotation animated:YES];
}


- (void)goodEvaluate:(UIButton *)sender
{
    _goodEvaluateView.tag = sender.tag;
    _goodEvaluateView.backgroundColor = [[UIColor darkTextColor] colorWithAlphaComponent:0.65];

    [_goodEvaluateView_Small.layer setCornerRadius:6];
    [_goodEvaluateView_Small.layer setBorderColor:[[UIColor whiteColor] CGColor]];//描边颜色
    [_goodEvaluateView_Small.layer setBorderWidth:2.0];//描边粗细

    [self.view addSubview:_goodEvaluateView];
}

- (void)badEvaluate:(UIButton *)sender
{
    _badEvaluateView.tag = sender.tag;
    _badEvaluateView.backgroundColor = [[UIColor darkTextColor] colorWithAlphaComponent:0.65];
    
    [_badEvaluateView_Small.layer setCornerRadius:6];
    [_badEvaluateView_Small.layer setBorderColor:[[UIColor whiteColor] CGColor]];//描边颜色
    [_badEvaluateView_Small.layer setBorderWidth:2.0];//描边粗细

    [self.view addSubview:_badEvaluateView];
}

- (IBAction)giveGoodEvaluation:(UIButton *)sender
{
    NSDictionary *dict = [_dataArray objectAtIndex:_goodEvaluateView.tag];    
    
    NSString *typeStr = [dict objectForKey:kRequestType];
    [PassValueClass sharedIntance].requestType = typeStr;
    [PassValueClass sharedIntance].evaluateStr = _goodEvaluateTxtView.text;
    [PassValueClass sharedIntance].evaluateType = @"1";
    [PassValueClass sharedIntance].requestID = [dict objectForKey:kRequestID];
    
    //--------------------1059---用户评价
    NSString *string    = [RequestCMD requestCMD:kBillEvaluation];
    NSMutableData *data = [RequestCMD getWantedData:string];
    [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kBillEvaluation];//1055---未评价订单

    if (!_HD)
    {
        _HD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:_HD];
        _HD.labelText = @"请稍后";
    }
    
    [_HD showAnimated:YES whileExecutingBlock:^{
        //对话框显示时需要执行的操作
        sleep(2);
    } completionBlock:^{
        //操作执行完后取消对话框
        [_HD removeFromSuperview];
        _HD = nil;
        [_goodEvaluateView removeFromSuperview];}];

}

- (IBAction)giveBadEvaluation:(UIButton *)sender
{
    NSDictionary *dict = [_dataArray objectAtIndex:_badEvaluateView.tag];
    NSString *typeStr = [dict objectForKey:kRequestType];
    [PassValueClass sharedIntance].requestType = typeStr;
    [PassValueClass sharedIntance].evaluateStr = _badEvaluateTxtView.text;
    [PassValueClass sharedIntance].evaluateType = @"0";
    [PassValueClass sharedIntance].requestID = [dict objectForKey:kRequestID];

    
    if (_badEvaluateTxtView.text == nil)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"为了您和他人的利益,请补充差评理由" message:nil delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [alert show];
    }
    else
    {
        //--------------------1059---用户差评
        NSString *string    = [RequestCMD requestCMD:kBillEvaluation];
        NSMutableData *data = [RequestCMD getWantedData:string];
        [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kBillEvaluation];//1061---用户差评
    
        if (!_HD)
        {
            _HD = [[MBProgressHUD alloc] initWithView:self.view];
            [self.view addSubview:_HD];
            _HD.labelText = @"请稍后";
        }
        [_HD showAnimated:YES whileExecutingBlock:^{
            //对话框显示时需要执行的操作
            sleep(2);
        } completionBlock:^{
            //操作执行完后取消对话框
            [_HD removeFromSuperview];
            _HD = nil;
            [_badEvaluateView removeFromSuperview];}];
    }
}

- (IBAction)removeBadView
{
    [_badEvaluateView removeFromSuperview];
}

- (IBAction)removeGoodView
{
    [_goodEvaluateView removeFromSuperview];
}


#pragma mark -TxtView Delegate - txtview代理

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if (_goodEvaluateTxtView)
    {
        if ([_goodEvaluateTxtView.text isEqualToString:@"请输入评论,可为空"])
        {
            _goodEvaluateTxtView.text = nil;
        }
    }
    if (_badEvaluateTxtView)
    {
        if ([_badEvaluateTxtView.text isEqualToString:@"请输入差评原因"])
        {
            _badEvaluateTxtView.text = nil;
        }
    }
}

#pragma mark - Map View - Map View

- (void)loadMap
{
    _mapView = [[BMKMapView alloc] init];
    CGRect rect12 =  CGRectMake(0, 0, 320, 415);
    _mapView.frame = rect12;
    _mapView.showsUserLocation = YES;
    _mapView.delegate = self;
    _myMapView = _mapView;
    
    [_myMapView addSubview:_mapView_Small];
    
    [self.view addSubview:_myMapView];
    _myMapView.hidden = YES;
}



- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]])
    {
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation
                                                                                   reuseIdentifier:@"myAnnotation"];
        
        newAnnotationView.pinColor = BMKPinAnnotationColorRed;
        newAnnotationView.animatesDrop = YES;
        return newAnnotationView;
    }
    return nil;
}

- (IBAction)hideMap
{
    _myMapView.hidden = YES;
}

@end
